;layui.define(['layer', 'jquery'], function (exports) {
    const $ = layui.jquery,
        layer = layui.layer;


    /**
     * ajax 基本封装
     * @param url 请求路径
     * @param jsonStr 请求参数 body
     * @param layer 弹框对象
     * @param type 请求方式
     * @param handleRes 处理请求结果
     */
    function ajax4json(url, jsonStr, type, handleRes) {
        const idx = layer.load(1);
        $.ajax({
            url: url,
            type: type,
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            data: jsonStr,
            statusCode: {
                200: function (res) {
                    handleRes(JSON.parse(res.responseText))
                },

                401: function () {
                    layer.alert("登录超时",function (){

                    top.location.reload();
                    })

                }
            },
            complete: function () {
                layer.close(idx);
            }
        });
    }

    function ajax(url, jsonStr, type, handleRes) {
        const idx = layer.load(1);
        $.ajax({
            url: url,
            type: type,
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            data: jsonStr,
            statusCode: {
                200: function (res) {
                    layer.msg(res.responseText, {icon: 6})
                    handleRes();
                },

                401: function () {
                    layer.alert("登录超时",function (){
                        top.location.reload();
                    })
                }
            },
            complete: function () {
                layer.close(idx);
            }
        });
    }

    const get = function (url, cb) {
        ajax(url, '', 'GET', cb);
    }
    const get4json = function (url, cb) {
        ajax4json(url, '', 'GET', cb);
    }
    const post4json = function (url, param, cb) {
        ajax4json(url, JSON.stringify(param), 'POST', cb)
    }
    const post = function (url, param, cb) {
        ajax(url, JSON.stringify(param), 'POST', cb)
    }
    const del = function (url, param, cb) {
        ajax(url, JSON.stringify(param), 'DELETE', cb)
    }
    const put = function (url, param, cb) {
        ajax(url, JSON.stringify(param), 'PUT', cb)
    }
    exports('ajax', function () {
        return {get, get4json, post, post4json, del, put}
    }());
})